<?php

namespace App\Http\Controllers\Api;

use App\Models\ParkingTimesCollection;
use App\Selection;
use Illuminate\Http\Request;
use App\Http\Controllers\AppBaseController;

class ParkingTimeCountController extends AppBaseController
{

    /**
     * 根据request构建查询条件
     *
     * @param $request
     * @param $parks
     * @return ParkingTimesCollection
     */
    private function queryBuild($request, $parks = [])
    {
        $model = new ParkingTimesCollection();
        $req_parks = $request->get('park_code');

        if(in_array("7100000288", $req_parks)){
            foreach ($req_parks as $k=>$v) {
                if($v == "7100000290" || $v == "7100000291"){
                    unset($req_parks[$k]);
                }
            }
        }

        if ($req_parks) {
            $model = $model->whereIn('park_code', $req_parks);
        } else {
            $model = $model->whereIn('park_code', $parks);
        }


        if ($request->get('start_time')) {
            $model = $model->where('hour', '>=', $request->get('start_time'));
        }

        if ($request->get('end_time')) {
            $model = $model->where('hour', '<=', $request->get('end_time'));
        }

        $model = $model->select();

        return $model;
    }


    /**
     * 查询字段定义
     *
     * @return array
     */
    private function selectField()
    {

        $filed = [
            'total',
            'time_0_30',
            'time_30_60',
        ];
        for ($i = 60; $i < 1440; $i += 60) {
            $filed[] = 'time_' . $i . '_' . ($i + 60);
        }
        $filed[] = 'time_1440';


        $sumField = collect($filed)->map(function ($item) {
            return \DB::raw('IFNULL(SUM(' . $item . '),0)as ' . $item);
        });

        return $sumField;
    }

    /**
     * 查询车流量方法
     *
     * @param $request
     * @return static
     */
    public function query(Request $request)
    {
        $this->validate($request, [
            'start_time' => 'date',
            'end_time' => 'date'
        ]);

        //拥有车场查询
        $parks = $this->getUserParks();
        $parkCode = $this->getParkCodes($parks);
        $sumField = $this->selectField()->push('type');

        $res = $this->queryBuild($request, $parkCode)->groupBy('type')->select($sumField->toArray())->get();
        $timeConfig = Selection::where('parent_id', 176)->orderBy('sort', 'asc')->get();
        $carType = Selection::where('parent_id', 185)->orderBy('sort', 'asc')->get();

        //查询数据组建
        $data = $timeConfig->map(function ($item) use ($carType, $res) {
            $value['name'] = $item->name;
            $value['total'] = 0;
            foreach ($carType->toArray() as $v) {
                $code = strtolower($v['code']);
                $row = $res->where('type', $v['id'])->first();
                if (!$row) {
                    $value[$code] = 0;
                    continue;
                }

                //一个字段
                $params = \GuzzleHttp\json_decode($item->params, true);
                if (count($params) < 2) {
                    $value[$code] = $row[$params[0]];
                    $value['total'] += $value[$code];
                    continue;
                }

                //多个时间段累加
                $value[$code] = 0;
                for ($i = $params[0]; $i < $params[1]; $i += 60) {
                    $field = 'time_' . $i . '_' . ($i + 60);
                    $value[$code] += $row[$field];
                }

                $value['total'] += $value[$code];
            }


            return $value;
        });

        return $this->sendResponse($data->toArray(), '查询成功');

    }


}
